package com.ssmfuse.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ocr.utils.impl.QuestionToResultImpl;
import com.ocr.utils.impl.SimilarityUtil;
import com.ssmfuse.Bean.BaiDuBean;
import com.ssmfuse.Bean.Page;
import com.ssmfuse.Bean.Result;
import com.ocr.utils.IOcrUtils;
import com.ssmfuse.Utils.WebUtil;
import com.ssmfuse.domain.Question;
import com.ssmfuse.mapper.QuestionMapper;
import com.ssmfuse.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.management.monitor.StringMonitor;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Controller层
 * @author 化粪池堵塞的凶手
 */

@Controller
@RequestMapping("/xue/api")
public class AccountController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private IOcrUtils ocrUtils;

    private static Boolean Success = false;

    /**
     * 图片查找
     * @param file
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @RequestMapping("/uploadimg")
    @ResponseBody      //把回传类转换成json
    public List<Result> uploadPhone(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException {
        //读取文件
        String path=uploadFile(file, request);
        //OCR
        ocrUtils.openClient();
        String ocrString = ocrUtils.getOcr(path);
        //解析json
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(ocrString);
        JsonNode words_result = jsonNode.get("words_result");
        List<BaiDuBean> list = mapper.readValue(words_result.toString(),new TypeReference<List<BaiDuBean>>() {});
        //字符拼接
        String stringSum="";
        for (BaiDuBean i:list) {
            if (i.getWords().matches("[a-zA-Z]+"))   //true:全文英文
            {
                stringSum+=" " +i.getWords();
            }
            else {
                stringSum+=i.getWords();
            }

        }
        //查找答案
        return selectQuestion(stringSum);
    }

    /**
     * 访查数据库找答案
     */
    public List<Result> selectQuestion(String stringsum){
        System.out.println("sum"+stringsum);
        //定义ListBean
        List<Result> results = new ArrayList<Result>();
        String regEx="[\n`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？]";
        String aa="";
        stringsum=stringsum.replaceAll(regEx,aa);
        if (stringsum.length()<3){
            Result result=new Result();
            result.setQuestion("没有找到题目");
            result.setDaan("null");
            result.setTijie("null");
            results.add(result);
            return results;
        }
        List<Question> questions = null;
        //通过数据库的Like方式查找相关数据
        questions = questionService.findQuestion_one(stringsum);
        //判断List是否为空
        if (questions!=null&&questions.size()>0){
            //bean转换
            results = QuestionToResultImpl.get(questions);
            return results;
        }
        try {
            List<String> keyWord;
            keyWord = SimilarityUtil.getKeyWord(stringsum,15);
            keyWord.forEach(System.out::println);
            if (keyWord.size()>=5){
                questions = questionService.findQuestion_five(keyWord.get(0),keyWord.get(1),keyWord.get(2),keyWord.get(3),keyWord.get(4));
            }
            else if (keyWord.size()>=3){
                questions = questionService.findQuestion(keyWord.get(0),keyWord.get(1),keyWord.get(2));
            }
            else if (keyWord.size()>=2){
                questions = questionService.findQuestion_two(keyWord.get(0),keyWord.get(1));
            }
            else if (keyWord.size()>=1){
                questions = questionService.findQuestion_one(keyWord.get(0));
            }
            System.out.println("----------------------keyword-----------------------------------");
            keyWord.forEach(System.out::println);

        }catch (Exception e){
            e.printStackTrace();
        }
        //判断List是否为空
        if (questions!=null&&questions.size()>0){
            //bean转换
            results = QuestionToResultImpl.get(questions);
            return results;
        }
        else {
            //FindAll查询 比较相似度符合条件的 存入临时list
            try {
                questions = questionService.questionList();
                QuestionToResultImpl.xiangSiGet(questions,stringsum,0.5);
            }catch (Exception e){
                e.printStackTrace();
            }
            //判断List是否为空
            if (results!=null&&results.size()>0){
                return results;
            }
            else {
                Result result=new Result();
                result.setQuestion("没有找到题目");
                result.setDaan("null");
                result.setTijie("null");
                results.add(result);
                return results;
            }
        }
    }

    /**
     * 上传
     * @param file
     * @param request
     * @return
     * @throws IOException
     */

    private String  uploadFile(MultipartFile file,HttpServletRequest request)

       throws IOException {

            String path=request.getSession().getServletContext().getRealPath("upload");

            String fileName=file.getOriginalFilename();

            File targetFile=new File(path,fileName);

            if(!targetFile.exists()){

                targetFile.mkdirs();

            }

            file.transferTo(targetFile);

            return targetFile.getAbsolutePath();

    }

    /**
     * 文本查找
     * @param word
     * @return
     */
    @RequestMapping("/TextSelect")
    @ResponseBody
    public List<Result> TextSelect(String word) {
        return selectQuestion(word);
    }

    /**
     * 显示所有的问题 管理界面用的
     * @param model
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/showQuestion")
    public String showQuestion(Model model,HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Question> questions = questionService.questionList();
        if (Success){

            request.getSession().setAttribute("myname","success");
            Success = false;
        }
        else {
            request.getSession().setAttribute("myname","");
        }

        request.getSession().setAttribute("show_question",questions);

        return "query";
    }
    /**
     * 更新问题
     * @param pp
     * @param name
     * @param answer
     * @param explain
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/update")
    public void update(int pp,String name,String answer,String explain,HttpServletRequest request,HttpServletResponse response) throws IOException {
        Question question= new Question();
        question.setId(pp);
        question.setQuestion_answer(answer);
        question.setQuestion_name(name);
        question.setQuestion_explain(explain);
        questionService.updateQuestion(question);
        Success=true;
        response.sendRedirect(request.getContextPath() +"/xue/api/page");
    }

    /**
     * 删除问题
     * @param pp
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/delete")
    public void delete(int pp,HttpServletRequest request,HttpServletResponse response) throws IOException {
        Question question= new Question();
        question.setId(pp);
        questionService.deleteQuestion(pp);
        Success=true;
        response.sendRedirect(request.getContextPath() +"/xue/api/page");
    }

    @RequestMapping("/insert")
    public void insertQuestion(String name,String answer,String explain,HttpServletRequest request,HttpServletResponse response) throws IOException {
        Question question = new Question(name, answer, explain);
        questionService.addQuestion(question);
        response.sendRedirect(request.getContextPath()+"/insert.jsp");
    }

    /**
     * 处理分页
     * @param request
     * @param response
     */
    @RequestMapping("/page")
    protected String page(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数 PageNo 和PageSize
        int pageNo = WebUtil.parseInt(request.getParameter("pageNo"),1);
        int pageSize = WebUtil.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        //2.调用service.page方法(pageNo,pageSize)
        Page<Question> page = questionService.page(pageNo,pageSize);
        System.out.println(page);
        //3.保存page对象到Request域中
        request.setAttribute("page",page);
        if (Success){

            request.getSession().setAttribute("myname","success");
            Success = false;
        }
        else {
            request.getSession().setAttribute("myname","");
        }

        //4.请求转发到pages/....jsp页面
//        request.getRequestDispatcher("../../query.jsp").forward(request,response);
//        response.sendRedirect(request.getContextPath() +"/xue/api/showPage");
//        response.sendRedirect(request.getContextPath()+"/query.jsp");
        return "query";
    }

    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest request,Model model){
        System.out.println(username);
        System.out.println(password);
        if("admin".equals(username) && "admin".equals(password)){
            System.out.println("登录成功");
            request.getSession().setAttribute("loginMessage",username);
            return "redirect:/index.jsp";
            }else {
                System.out.println("登录失败");
                model.addAttribute("message","登录失败，账号密码错误");
                return "redirect:/User.jsp";
            }
        }
}
